package com.example.arffrecorder;

import Utils.ARFFFileWriter;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.arffrecorder.ARFFLocationService.LocalBinder;

public class RecordingActivity extends Activity {

	boolean serviceBound = false;
	ARFFLocationService mService;
	Button startButton, stopButton;
	Intent serviceIntent;
	private EditText fileNameTextArea;
	private String nameOfFile;
	private boolean serviceStarted = false;
	//
	private static final String TAG = "SendingData";
	private Intent intent;
	private String ox, oy, oz;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recording);

		startButton = (Button) findViewById(R.id.start_record);
		startButton.setOnClickListener(startSensorReading);
		stopButton = (Button) findViewById(R.id.stop_record);
		stopButton.setOnClickListener(stopSensorReading);
		stopButton.setEnabled(false);
		fileNameTextArea = (EditText) findViewById(R.id.fileName);
		fileNameTextArea.addTextChangedListener(watcher);
		intent = new Intent(this, ARFFLocationService.class);
	}
	
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	ox = intent.getStringExtra("ox");
        	oy = intent.getStringExtra("oy"); 
        	oz = intent.getStringExtra("oz"); 
        	displayInfo(ox,oy,oz);
        }
    }; 
    
    /**
     * save data from the edit file in a variable so that it can be passed when the orientation change
     */
	TextWatcher watcher = new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			nameOfFile = fileNameTextArea.getText().toString();
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			
		}
	};
	/** Listener for startButton 
	 * 
	 */
	View.OnClickListener startSensorReading = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			if (isFileNameValid()){
				
				ImageView recordImage = (ImageView) findViewById(R.id.recordImage);
				recordImage.setImageResource(R.drawable.record_start);
				startButton = (Button)findViewById(R.id.start_record);
				stopButton = (Button) findViewById(R.id.stop_record);
				stopButton.setEnabled(true);
				startButton.setEnabled(false);
				if (serviceBound == false) {
					serviceBound = true;
					EditText fileName = (EditText) findViewById(R.id.fileName);
					fileName.setEnabled(false);
					intent.putExtra("fileName", nameOfFile + ".arff");
					if (!serviceStarted){
						startService(intent);
						serviceStarted = true;
					}
					
					bindService(intent, mConnection, Context.BIND_AUTO_CREATE);		
					registerReceiver(broadcastReceiver, new IntentFilter(ARFFLocationService.BROADCAST_ACTION));
				}
			}
		}
	};
	/** Listener for stopButton
	 * 
	 */
	View.OnClickListener stopSensorReading = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			ImageView recordImage = (ImageView) findViewById(R.id.recordImage);
			recordImage.setImageResource(R.drawable.record_stop);
			
			startButton = (Button)findViewById(R.id.start_record);
			stopButton = (Button) findViewById(R.id.stop_record);
			
			startButton.setEnabled(true);
			stopButton.setEnabled(false);
			if (serviceBound) {
				EditText fileName = (EditText) findViewById(R.id.fileName);
				fileName.setEnabled(true);		
				stopService(intent);
				
				unregisterReceiver(broadcastReceiver);
				unbindService(mConnection);
				serviceBound = false;
			}
		}
	};

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.recording, menu);
		return true;
	}
	/**
	 * actions to be taken if one item from the menu is chosen
	 */
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.home_page:

			Intent i = new Intent(RecordingActivity.this, MainScreen.class);
			startActivity(i);
			return true;
		case R.id.help:
			Toast.makeText(RecordingActivity.this,
					"Press start button to record data from accelerometer",
					Toast.LENGTH_SHORT).show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	protected void onResume() {
		super.onResume();
		System.out.println("resume" + serviceBound);
		if (serviceBound){
			if (!serviceStarted){
				startService(intent);
				serviceStarted = true;
			}
			bindService(intent, mConnection, Context.BIND_AUTO_CREATE);	
			registerReceiver(broadcastReceiver, new IntentFilter(ARFFLocationService.BROADCAST_ACTION));
		}
	}

	protected void onPause() {
		super.onPause();
		System.out.println("pause");
	}

	@Override
	protected void onStop() {
		
		super.onStop();
		System.out.println("stop activity" + serviceBound);
		if (isFinishing() && serviceBound){
			unbindService(mConnection);
			serviceBound = false;
			unregisterReceiver(broadcastReceiver);
			//stopService(intent);
		}
	}
	
	//in case orientation changes do not recreate activity (stop service)
	@Override
    public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		//System.out.println(nameOfFile);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
			setContentView(R.layout.activity_recording_land);
			EditText fileName = (EditText) findViewById(R.id.fileName);
			EditText oxText = (EditText) findViewById(R.id.ox_data);
			EditText oyText = (EditText) findViewById(R.id.oy_data);
			EditText ozText = (EditText) findViewById(R.id.oz_data);
			fileName.setText(nameOfFile);
			
			oxText.setText(ox); 
			oyText.setText(oy);
			ozText.setText(ox);
			
			Button newStartButton = (Button) findViewById(R.id.start_record);
			Button newStopButton = (Button) findViewById(R.id.stop_record);
			
			newStartButton.setOnClickListener(startSensorReading);
			newStopButton.setOnClickListener(stopSensorReading);
			
			newStartButton.setEnabled(startButton.isEnabled());
			newStopButton.setEnabled(stopButton.isEnabled());
			
			ImageView recordImg = (ImageView)findViewById(R.id.recordImage);
			
			if(stopButton.isEnabled()){
				recordImg.setImageResource(R.drawable.record_start);
			}
			else{
				recordImg.setImageResource(R.drawable.record_stop);
			}
		}
		else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
			setContentView(R.layout.activity_recording);
		EditText fileName = (EditText) findViewById(R.id.fileName);
		
		
		EditText oxText = (EditText) findViewById(R.id.ox_data);
		EditText oyText = (EditText) findViewById(R.id.oy_data);
		EditText ozText = (EditText) findViewById(R.id.oz_data);
		fileName.setText(nameOfFile);
		
		oxText.setText(ox); 
		oyText.setText(oy);
		ozText.setText(ox);
		
	
		Button newStartButton = (Button) findViewById(R.id.start_record);
		Button newStopButton = (Button) findViewById(R.id.stop_record);

		newStartButton.setOnClickListener(startSensorReading);
		newStopButton.setOnClickListener(stopSensorReading);

		newStartButton.setEnabled(startButton.isEnabled());
		newStopButton.setEnabled(stopButton.isEnabled());
		
		ImageView recordImg = (ImageView)findViewById(R.id.recordImage);
		
		if(stopButton.isEnabled()){
			recordImg.setImageResource(R.drawable.record_start);
		}
		else{
			recordImg.setImageResource(R.drawable.record_stop);
		}
	} 	
	
	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// We've bound to LocalService, cast the IBinder and get
			// LocalService instance
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			//myMessenger = new Messenger (service);
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			serviceBound = false;
		}
	
	};
	/** displayInfo
     * 
     */
	public void displayInfo(String ox, String oy, String oz){
		
		EditText oxData = (EditText) findViewById(R.id.ox_data);
		oxData.setText(ox);

		EditText oyData = (EditText) findViewById(R.id.oy_data);
		oyData.setText(oy);

		EditText ozData = (EditText) findViewById(R.id.oz_data);
		ozData.setText(oz);
	}
	/**method for checking if the filename is valid for starting recording
	 * 
	 */
	public boolean isFileNameValid(){
		EditText fileName = (EditText) findViewById(R.id.fileName);
		nameOfFile = fileName.getEditableText().toString();
		if (fileName != null)
			if (ARFFFileWriter.getInstance().isFileNameValid(nameOfFile)){
				if (ARFFFileWriter.getInstance().fileExists(nameOfFile + ".arff")){
					System.out.println("File with this name already exists!");
					Toast.makeText(this, "File with this name already exists!", Toast.LENGTH_SHORT).show();
					return false;
				}
				else 
					return true;
			}
			else {
				System.out.println("Invalid filename!");
				Toast.makeText(this, "Invalid filename!", Toast.LENGTH_SHORT).show();
				return false;
			}
		else{
			System.out.println("Unexpected input error!");
			Toast.makeText(this, "Unexpected input error!", Toast.LENGTH_SHORT).show();
			return false;
		}
	}	
	/**
	 * get file extension from the option chosen by the user from the combobox
	 */
	/*public String getExtension(){
		Spinner extension = (Spinner) findViewById(R.id.spinner1);
		if (extension != null)
			return extension.getSelectedItem().toString();
		else
			return "";
	}*/
}